import { defineStore } from "pinia2";
import { pinia3 } from "@/store";
import { queryVideoList } from "@/api/news";
import dayjs from "dayjs";
import { insertAdvert } from "@/utils";
function getYouTubeVideoId(url: string): string | null {
  const regex =
    /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
  const match = url.match(regex);
  return match ? match[1] : null;
}

export const useCachedVideoStore = defineStore({
  id: "cached-video",
  state: () => ({
    page: 1,
    cachedVideoList: [] as any[],
    tabVideoList: [] as any[],
    videoLoadMoreStatus: "loadmore" as "loadmore" | "loading" | "nomore"
  }),
  actions: {
    fetchVideos() {
      return new Promise((resolve, reject) => {
        if (this.videoLoadMoreStatus === "nomore") return reject();
        this.videoLoadMoreStatus = "loading";
        queryVideoList(this.page++)
          .then((res: any) => {
            const data = (res || []).map((item: any) => {
              return {
                id: item.id,
                src: item.image,
                title: item.title,
                time: item.addtime
                  ? dayjs(+String(item.addtime).padEnd(13, "0")).format(
                      "YYYY-MM-DD HH:mm:ss"
                    )
                  : "",
                author: item.author,
                link: item.link,
                type: "video",
                imgWidth: "100%",
                imgHeight: "auto",
                // 视频页面使用
                video_url: item.link,
                youtubeId: getYouTubeVideoId(item.link) || "",
                video_cover: item.image,
                add_username: item.author,
                content: item.title
              };
            });
            if (data.length < 6) {
              this.videoLoadMoreStatus = "nomore";
            } else {
              this.videoLoadMoreStatus = "loadmore";
            }

            const lastAdvertIndex = unref(this.cachedVideoList).findLastIndex(
              (item: any) => item.type === "advert"
            );
            let lastEles = [];
            let preEles = [];
            if (lastAdvertIndex !== -1) {
              lastEles = unref(this.cachedVideoList).slice(lastAdvertIndex + 1);
              preEles = unref(this.cachedVideoList).slice(
                0,
                lastAdvertIndex + 1
              );
            } else {
              preEles = [];
              lastEles = [...unref(this.cachedVideoList)];
            }
            const currData = insertAdvert(
              [...lastEles, ...data],
              { type: "advert", source: "news" },
              5
            );

            this.tabVideoList = preEles.concat(currData);
            this.cachedVideoList = this.cachedVideoList.concat(data);
            resolve(this.cachedVideoList);
          })
          .catch(() => {
            reject();
            this.videoLoadMoreStatus = "loadmore";
          });
      });
    },
    setCachedVideos(videos: any[]) {
      this.cachedVideoList = videos;
    },
    resetCachedVideos() {
      this.cachedVideoList = [] as string[];
    }
  }
});
export function useCachedVideoStoreHook() {
  return useCachedVideoStore(pinia3);
}
